// #ifdef H5
 
import COS from 'cos-js-sdk-v5'
 


const Bucket = "wuyan-1316599272"; /* 填入您自己的存储桶，必须字段 */
const Region = 'ap-guangzhou'; /* 存储桶所在地域，例如ap-beijing，必须字段 */


const cos = new COS({
	SecretId: 'AKIDd3RfcLTpuiHZcWDvZ3JNIBsJTTDiz1nI',
	SecretKey: 'MWWO6d0BJH3aw5EDyUotlPHzUkmaBXnq',
})

// #ifdef H5
export function h5UploadFile(blob, fileNameKey) {
	//上传图片
	return new Promise(function(resolve, reject) {
		cos.putObject({
			Bucket: Bucket,
			Region: Region,
			Key: `${fileNameKey}`,
			Body: blob,
		}, function(err, data) {
			 
			if (!err) {
				resolve(data);
			} else {
				reject(err);
			}
		});
	})
}

// base64转blob
export function parseBlob(dataurl) {
	var arr = dataurl.split(',');
	var mime = arr[0].match(/:(.*?);/)[1];
	var bstr = atob(arr[1]);
	var n = bstr.length;
	var u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

// 随机生成字符串做名字
export function getRandomString(len, type) {
	let _charStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
		min = 0,
		max = _charStr.length - 1,
		_str = ''; //定义随机字符串 变量
	//判断是否指定长度，否则默认长度为15
	len = len || 15;
	//循环生成字符串
	for (var i = 0, index; i < len; i++) {
		index = (function(randomIndexFunc, i) {
			return randomIndexFunc(min, max, i, randomIndexFunc);
		})(function(min, max, i, _self) {
			let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
				numStart = _charStr.length - 10;
			if (i == 0 && indexTemp >= numStart) {
				indexTemp = _self(min, max, i, _self);
			}
			return indexTemp;
		}, i);
		_str += _charStr[index];
	}
	return _str + '.' + type
}

//bolburl转file
export function parseFile(src, name) {
	let that = this
	return new Promise((resolve, reject) => {
		let xhr = new XMLHttpRequest()
		xhr.open('GET', src, true)
		xhr.responseType = 'blob'
		xhr.onload = function(e) {
			if (this.status == 200) {
				let myBlob = this.response
				let files = new window.File(
					[myBlob],
					name, {
						type: myBlob.type
					}
				) // myBlob.type 自定义文件名
				resolve(files)
			} else {
				reject(false)
			}
		}
		xhr.send()
	})
}
// #endif

// #ifdef MP-WEIXIN
export function wxUploadFile(filePath, fileName) {
	return new Promise(function(resolve, reject) {
		cos.postObject({
			Bucket: Bucket,
			/* 必须 */
			Region: Region,
			/* 必须 */
			Key: `/image/${fileName}`,
			/* 必须 */
			FilePath: filePath,
			onProgress: function(info) {
				console.log("[cos.postObject-seccess]", JSON.stringify(info));
			}
		}, function(err, data) {
			console.log("[cos.postObject-err]", err || data);
			resolve(data.headers.location)
		});
	})
}
// #endif